package cn.qdhlm.frontendprocessor.model.memory;


import cn.qdhlm.frontendprocessor.common.util.ComUtil;
import cn.qdhlm.frontendprocessor.common.util.JsonUtil;
import lombok.Data;
import lombok.extern.log4j.Log4j2;

import java.util.*;

/**
 * @Name: SocketSessionMap
 * @Description: SocketSessionMap
 * @Author : jiangcs
 */
@Log4j2
@Data
public class SocketSessionMap {
    /**
     * key: socketId
     * value: socketSession
     */
    private static Map<String, SocketSession> sessionMap = new HashMap<>(1024);

    public static Map<String, SocketSession> getMap() {
        return sessionMap;
    }

    public static void add(String socketId, SocketSession socketSession) {
        // 创建时间
        socketSession.setCreateTime(ComUtil.formatDateTime(new Date(), "yyyy-MM-dd HH:mm:ss"));

        sessionMap.put(socketId, socketSession);

        log.info("socketSessionMap add: socketId[{}] => {}", socketId, JsonUtil.safeJsonStr(socketSession));
    }

    public static void update(String socketId, SocketSession socketSession) {
        // 更新时间
        socketSession.setUpdateTime(ComUtil.formatDateTime(new Date(), "yyyy-MM-dd HH:mm:ss"));

        sessionMap.put(socketId, socketSession);

        log.info("socketSessionMap update: socketId[{}] => {}", socketId, JsonUtil.safeJsonStr(socketSession));
    }

    public static SocketSession get(String socketId) {
        return sessionMap.get(socketId);
    }

    public static SocketSession remove(String socketId) {
        SocketSession socketSession = sessionMap.remove(socketId);

        log.info("socketSessionMap remove: socketId[{}] => {}", socketId, JsonUtil.safeJsonStr(socketSession));

        return socketSession;
    }

    public static void removeByCollectorNo(String collectorNo) {
        List<String> socketIdList = new ArrayList<>();

        SocketSession socketSession;
        for (String socketId : sessionMap.keySet()) {
            socketSession = sessionMap.get(socketId);
            if (collectorNo.equals(socketSession.getCollectorNo())) {
                socketIdList.add(socketId);
            }
        }

        if (socketIdList.size() > 0) {
            for (String socketId : socketIdList) {
                socketSession = sessionMap.remove(socketId);
                log.info("socketSessionMap removeByCollectorNo: collectorNo[{}] => {}", collectorNo, JsonUtil.safeJsonStr(socketSession));
            }
        }
    }
}
